import ProposalAPI from '@/api/Proposal';
import { Box, FormSection, SimpleEditor, useCall, useFormValue, useSimpleMemo } from '@/components';
import { SelectProduct } from '@/pages/components';
import { catchAndScrollFor } from '@/utils/fp';
import { Form, Input, Radio } from 'antd';
import React, { cloneElement, forwardRef, useEffect, useImperativeHandle } from 'react';
import { useDefinitionData, useUpdateDefinition } from './Context';

const itemProps = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const names = {
  riskType: ['riskType'],
  productCode: ['productDefine', 'productCode'],
  productName: ['productDefine', 'productName'],
  productShort: ['productDefine', 'productShort'],
  productDetail: ['productDefine', 'productDetail'],
};

const rules = {
  riskType: [{ required: true, message: '请选择主附险类型' }],
  productCode: [{ required: true, message: '请选择产品代码' }],
  productShort: [{ required: true, message: '请输入产品简称' }],
};

const riskTypeRadioOptions = [
  { label: '主险', value: '1' },
  { label: '附加险', value: '2,3,4,5' },
];

const SelectProductWithRiskType = ({ form, value, children, ...props }) => {
  const productType = useFormValue(form, ['riskType']);
  return (
    <SelectProduct {...props} onService={useCall((formData) => [{ ...formData, productType }])}>
      {cloneElement(children, { value })}
    </SelectProduct>
  );
};

BasicConfig = forwardRef(BasicConfig);

function BasicConfig(props, ref) {
  const definitionData = useDefinitionData();
  const productDefine = useSimpleMemo(definitionData?.productDefineList?.[0] ?? null);
  const productType = productDefine?.productType ?? null;
  const setDefinitionData = useUpdateDefinition();
  const [form] = Form.useForm();

  useEffect(() => {
    const riskType = form.getFieldValue('riskType');
    if (productType && riskType.indexOf(productType) === -1) {
      form.setFieldsValue({
        riskType: productType === '1' ? '1' : '2,3,4,5',
      });
    }
  }, [productType]);

  useEffect(() => {
    if (productDefine) {
      form.setFieldsValue({ productDefine });
    }
  }, [productDefine]);

  const onSave = useCall(async () => {
    const formData = await form.validateFields().catch(catchAndScrollFor(form));
    const definitionPayload = {
      ...definitionData,
      productDefineList: [{ ...productDefine, ...formData.productDefine }],
    };
    await ProposalAPI.insert(definitionPayload);
    setDefinitionData(definitionPayload);
  });

  useImperativeHandle(
    ref,
    () => ({
      onSave,
    }),
    [],
  );

  const onSelectProduct = useCall(async ([prodItem]) => {
    const data = await ProposalAPI.byCode({ Code: prodItem.productCode });
    if (data?.data) {
      setDefinitionData(data.data);
    }
  });

  return (
    <FormSection title='选择产品'>
      <Box px={3} component={Form} form={form} {...itemProps}>
        <Form.Item name={names.riskType} rules={rules.riskType} label='主附险类型' initialValue='1'>
          <Radio.Group options={riskTypeRadioOptions} />
        </Form.Item>
        <Form.Item name={names.productCode} rules={rules.productCode} label='产品代码'>
          <SelectProductWithRiskType form={form} onOk={onSelectProduct}>
            <Input readOnly />
          </SelectProductWithRiskType>
        </Form.Item>
        <Form.Item name={names.productName} label='产品名称'>
          <Input readOnly />
        </Form.Item>
        {productType === '1' && (
          <>
            <Form.Item name={names.productShort} rules={rules.productShort} label='产品简称'>
              <Input />
            </Form.Item>

            <Form.Item name={names.productDetail} label='产品简介'>
              <SimpleEditor />
            </Form.Item>
          </>
        )}
      </Box>
    </FormSection>
  );
}

export default BasicConfig;
